﻿//------------------------------------------------------------
// Author: 烟雨迷离半世殇
// Mail: 1778139321@qq.com
// Data: 2020年1月4日 20:55:45
//------------------------------------------------------------

using System;
using System.Collections.Generic;


namespace NKG_MVVM_UI
{
    public class VMManager : SingletonTemplate<VMManager>
    {
        public Dictionary<Type, AViewModel> AllViewModels =
            new Dictionary<Type, AViewModel>();

        /// <summary>
        /// 获取VM
        /// </summary>
        public T GetVM<T>() where T : AViewModel
        {
            AViewModel tempViewModel;
            if (AllViewModels.ContainsKey(typeof(T)))
            {
                tempViewModel = AllViewModels[typeof(T)];
                return (T) tempViewModel;
            }

            Console.WriteLine("要获取的VM不存在");
            return null;
        }

        /// <summary>
        /// 创建VM
        /// </summary>
        public T CreateVM<T>() where T : AViewModel
        {
            AViewModel tempViewModel;
            if (AllViewModels.ContainsKey(typeof(T)))
            {
                //TODO：支持同一种类VM的多个实例
                Console.WriteLine("已经有了同种VM，请勿重复创建！");
                return null;
            }
            else
            {
                tempViewModel = ViewModelFactory.FetchViewModel<T>();
                AllViewModels.Add(typeof(T), tempViewModel);
                return (T) tempViewModel;
            }
        }

        /// <summary>
        /// 回收VM
        /// </summary>
        public void ReleaseVM(AViewModel aViewModel)
        {
            if (AllViewModels.Remove(aViewModel.GetType()))
            {
                ViewModelFactory.RecycleViewModel(aViewModel);
            }
            else
            {
                Console.WriteLine("要回收的VM不存在");
            }
        }
    }
}